package com.sptpc.learnspring.global.exception;

import com.sptpc.learnspring.global.response.GlobalResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * 统一异常处理
 * 1、业务异常的拦截和处理
 * 2、Spring框架异常的转换
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    //---------- 处理业务异常 ----------
    @ExceptionHandler(BusinessException.class)
    public GlobalResponse handleError(BusinessException e) {
        log.error("业务服务异常", e);
        return GlobalResponse
                .builder()
                .code(e.getResultCode().getCode())
                .msg(e.getMessage())
                .build();
    }

    //---------- 对spring的异常提供转换 ----------
    @ExceptionHandler(BindException.class)
    public GlobalResponse handleError(BindException e) {
        log.warn("API参数绑定异常", e);
        FieldError error = e.getFieldError();
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return GlobalResponse
                .builder()
                .code(HttpServletResponse.SC_BAD_REQUEST)
                .msg(message)
                .build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public GlobalResponse handleError(MethodArgumentNotValidException e) {
        log.warn("API参数无效", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return GlobalResponse
                .builder()
                .code(HttpServletResponse.SC_BAD_REQUEST)
                .msg(message)
                .build();
    }

}
